import { createRouter, createWebHistory } from "vue-router";
import tool from "../utils/tool.js";
import { ElMessage } from "element-plus";

// 引入组件
import Login from "@/views/framework/login/index.vue";
import Layout from "../layout/index.vue";
import Home from "@/views/framework/home/index.vue";
import Error from "@/views/framework/404/index.vue";
import InternationalSetting from "@/views/setting/internationalSetting/index.vue";

// 临时组件
import FormDesigner from "@/views/sysUtils/formDesigner/designer.vue";
import SchemaList from "@/views/sysUtils/formDesigner/index.vue";
import CodeGen from "@/views/sysUtils/codeGen/index.vue";
import CodeGenDemo from "@/views/demo/codeGenDemo/index.vue";

import XEUtils from "xe-utils";

const routes = [
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  {
    path: "/",
    name: "Layout",
    component: Layout,
    children: [
      {
        path: "home",
        name: "Home",
        component: Home,
      },
      {
        path: "international-setting",
        name: "InternationalSetting",
        component: InternationalSetting,
      },
      {
        path: "form-designer",
        name: "FormDesigner",
        component: FormDesigner,
      },
      {
        path: "schema-list",
        name: "SchemaList",
        component: SchemaList,
      },
      {
        path: "code-gen",
        name: "CodeGen",
        component: CodeGen,
      },
      {
        path: "code-gen-demo",
        name: "CodeGenDemo",
        component: CodeGenDemo,
      },
    ],
  },
  {
    path: "/:catchAll(.*)",
    name: "error",
    component: Layout,
    children: [
      {
        path: "/:catchAll(.*)",
        name: "404",
        component: Error,
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

var isGetRouter = false;
const routeWhiteList = ["/login"];
// 路由守卫
router.beforeEach((to, from) => {
  // 登录页面
  if (to.path == "/login") {
    isGetRouter = false;
  }

  // 判断token，没有token时跳转至登录页
  let token = tool.session.get("token");
  let token_id = new URLSearchParams(window.location.search).get("token_id");
  if (!token && !token_id && routeWhiteList.indexOf(to.path) === -1) {
    ElMessage.warning("请先登录");
    return { path: "/login" };
  }

  // 加载动态路由
  if (!isGetRouter) {
    // 得到接口得到的动态路由
    const apiMenus = tool.session.get("menus");
    // 处理动态路由
    if (apiMenus != null && apiMenus.length != 0) {
      const menus = filterAsyncRouter(JSON.parse(apiMenus));
      const menuRouter = XEUtils.toTreeArray(menus); // 扁平化路由

      menuRouter.forEach((item) => {
        router.addRoute("Layout", item);
      });

      isGetRouter = true;

      // 处理刷新后空白页面的问题
      if (to.name === "404") {
        router.push(to.path);
      }
    }
  }
});

// 获取当前路由列表
router.getAllMenus = function () {
  const apiMenus = tool.session.get("menus");
  let menus = [];
  if (apiMenus) {
    menus = filterAsyncRouter(JSON.parse(apiMenus));
  }
  return menus;
};

function filterAsyncRouter(routerMap) {
  const accessedRoutes = [];
  routerMap.forEach((item) => {
    // 路由对象
    let route = {
      path: item.path,
      name: item.name,
      component: loadComponent(item.url && item.url.endsWith(".vue") ? item.url : item.url + "/index.vue"),
      children: item.children ? filterAsyncRouter(item.children) : undefined, // 遍历子集目录
    };
    accessedRoutes.push(route);
  });
  return accessedRoutes;
}

const modules = import.meta.glob("/src/views/**/*.vue");
function loadComponent(url) {
  return modules[`/${url}`] || modules["/src/views/framework/404/index.vue"];
}

export default router;
